package cn.stylefeng.guns.utils.word;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * freemarker 根据模板生成word
 */
public class WordUtil {

    // ftl模板目录
    private String ftlUrl = "F:/";
    // ftl模板名称
    private String ftlName = "test.ftl";
    // 输出doc文件目录
    private String outUrl = "F:/";
    // 输出文件名称
    private String outFileName = "test.doc";

    /**
     * 获取word填充数据
     *
     * @param resumeVo
     * @return
     */
    private static Map<String, String> getData(TestVo resumeVo) {
        Map<String, String> map = new HashMap<>();
        map.put("name", resumeVo.getName());
        map.put("sex", resumeVo.getSex());
        map.put("age", resumeVo.getAge());
        map.put("phone", resumeVo.getPhone());
        map.put("email", resumeVo.getEmail());
        map.put("school", resumeVo.getSchool());
        map.put("major", resumeVo.getMajor());
        map.put("nation", resumeVo.getNation());
        return map;
    }

    /**
     * 根据模板生成word
     */
    public void beanToWord(TestVo culturalActivity) throws IOException, TemplateException {
        Map<String, String> map = getData(culturalActivity);
        //Configuration用于读取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
         * 指定ftl文件所在目录的路径,而不是ftl文件的路径
         */
        //指定路径的第一种方式(根据某个类的相对路径指定)
        //configuration.setClassForTemplateLoading(this.getClass(),"");
        //指定路径的第二种方式,我的路径是C:/a.ftl
        configuration.setDirectoryForTemplateLoading(new File(ftlUrl));

        String outFileUrl = outUrl + "/" + outFileName;
        // 输出文档路径及名称
        File outFile = new File(outFileUrl);

        //以utf-8的编码读取ftl文件
        Template template =  configuration.getTemplate(ftlName,"utf-8");

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
        template.process(map, out);
        out.close();
        System.out.println(outFileUrl);
    }

    public static void main(String[] args) {
        TestVo culturalActivity = new TestVo();
        culturalActivity.setName("苏州市");
        culturalActivity.setSex("男");
        culturalActivity.setAge("22");
        culturalActivity.setPhone("19979759191");
        culturalActivity.setEmail("111111111@qq.com");
        culturalActivity.setNation("汉");
        culturalActivity.setSchool("清华大学");
        culturalActivity.setMajor("测控技术");
        try {
            WordUtil wordUtil = new WordUtil();
            wordUtil.beanToWord(culturalActivity);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        System.out.println("好了");
    }
}